package com.itheima.datastructure.deque;

import java.util.Iterator;

/*
基于双向环形链表实现双端队列
 */
public class LinkedListDeque<E> implements Deque<E>,Iterable<E>{
    static class Node<E>{
        Node<E> prev;
        E value;
        Node<E> next;

        public Node(Node<E> prev, E value, Node<E> next) {
            this.prev = prev;
            this.value = value;
            this.next = next;
        }
    }

    int capacity;
    int size;
    Node<E> sentiel=new Node<>(null,null,null);

    public LinkedListDeque(int capacity){
        this.capacity=capacity;
        sentiel.next=sentiel;
        sentiel.prev=sentiel;
    }
    @Override
    public boolean offerFirst(E e) {
        if(isFull()){
            return false;
        }
        Node<E> a=sentiel;
        Node<E> b=sentiel.next;
        Node<E> added=new Node<>(a,e,b);
        a.next=added;
        b.prev=added;
        size++;
        return true;
    }

    @Override
    public boolean offerLast(E e) {
        if(isFull()){
            return false;
        }
        Node<E> a=sentiel.prev;
        Node<E> b=sentiel;
        Node<E> added=new Node<>(a,e,b);
        a.next=added;
        b.prev=added;
        size++;
        return true;
    }

    @Override
    public E pollFirst() {
        if(isEmpty()){
            return null;
        }
        Node<E> a=sentiel;
        Node<E> removed=sentiel.next;
        Node<E> b=removed.next;
        a.next=b;
        b.prev=a;
        size--;
        return removed.value;
    }

    @Override
    public E pollLast() {
        if(isEmpty()){
            return null;
        }
        Node<E> b=sentiel;
        Node<E> removed=sentiel.prev;
        Node<E> a=removed.prev;
        a.next=b;
        b.prev=a;
        size--;
        return removed.value;
    }

    @Override
    public E peekFirst() {
        if(isEmpty()){
            return null;
        }
        return sentiel.next.value;
    }

    @Override
    public E peekLast() {
        if(isEmpty()){
            return null;
        }
        return sentiel.prev.value;
    }

    @Override
    public boolean isEmpty() {
        return size==0;
    }

    @Override
    public boolean isFull() {
        return size==capacity;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            Node<E> p=sentiel.next;
            @Override
            public boolean hasNext() {
                return p!=sentiel;
            }

            @Override
            public E next() {
                E value=p.value;
                p=p.next;
                return value;
            }
        };
    }
}
